package com.yizisu.playerlibrary.view.video_view.view

import android.content.Context
import android.util.AttributeSet
import android.view.View
import androidx.appcompat.widget.AppCompatImageView
import com.yizisu.playerlibrary.R
import com.yizisu.playerlibrary.view.video_view.helper.IPlayerConfig
import com.yizisu.playerlibrary.view.video_view.helper.IPlayerHelper


/**
 * 播放视频时，屏幕锁
 */
open class PlayerScreenLockView @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = 0
) : AppCompatImageView(
    context,
    attrs,
    defStyleAttr
), IPlayerHelper {

    private var playerConfig: IPlayerConfig? = null
    private val enableGestureData
        get() = playerConfig?.screenNotLockData


    override fun onAttachPlayerConfig(playerConfig: IPlayerConfig) {
        super.onAttachPlayerConfig(playerConfig)
        this.playerConfig = playerConfig
        onEnableGestureChange(enableGestureData?.value)
        setOnClickListener {
            if (enableGestureData?.value != false) {
                postHideWhenLock()
                playerConfig.updateScreenNotLock(false)
                playerConfig.playerControllerBarHelperData.value?.hide(0)
            } else {
                removeCallbacks(lockHideRun)
                playerConfig.updateScreenNotLock(true)
                playerConfig.playerControllerBarHelperData.value?.hide(0)
            }
        }
        enableGestureData?.observeForever(::onEnableGestureChange)
    }


    override fun onDetachedPlayerConfig(playerConfig: IPlayerConfig) {
        super.onDetachedPlayerConfig(playerConfig)
        enableGestureData?.removeObserver(::onEnableGestureChange)
    }

    private fun onEnableGestureChange(data: Boolean?) {
        if (data != false) {
            setImageResource(R.drawable.icon_un_lock)
        } else {
            setImageResource(R.drawable.icon_lock)
        }
    }


    private val lockHideRun = Runnable {
        visibility = View.INVISIBLE
    }

    /**
     * 当锁定后，延时隐藏
     */
    fun postHideWhenLock() {
        visibility = View.VISIBLE
        removeCallbacks(lockHideRun)
        postDelayed(lockHideRun, 2000)
    }
}